package com.llh.demo4session.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * <p>CreatedAt: 2020/9/3 10:47</p>
 *
 * @author llh
 */
@Controller
public class DemoController {
    @Value("${server.port}")
    private Integer port;

    @GetMapping("")
    public ModelAndView hello(ModelAndView mv, HttpSession session) {
        session.setAttribute("aaa", LocalDateTime.now());
        Object shared = session.getAttribute("shared");
        if (shared == null) {
            String value = "I am shared from " + port;
            shared = value;
            session.setAttribute("shared", value);
        }
        Object aaa = session.getAttribute("aaa");
        mv.addObject("time", aaa);
        mv.addObject("shared", shared);
        mv.setViewName("hello");
        return mv;
    }

    @GetMapping("login")
    public ModelAndView loginPage(ModelAndView mv) {
        mv.setViewName("login");
        return mv;
    }

    @PostMapping("login")
    public ModelAndView login(HttpServletRequest request, ModelAndView mv) {
        String username = request.getParameter("username");
        username = StringUtils.isEmpty(username) ? "Tom" : username;
        System.out.println("request = " + username);
        AuthenticationToken token = new UsernamePasswordToken(username, "123");
        try {
            SecurityUtils.getSubject().login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        mv.setViewName("redirect:/welcome");
        return mv;
    }

    @GetMapping("welcome")
    public ModelAndView needPage(ModelAndView mv) {
        mv.addObject("name", SecurityUtils.getSubject().getPrincipal());
        mv.setViewName("welcome");
        return mv;
    }

    @GetMapping("401")
    public ModelAndView page401(ModelAndView mv) {
        mv.setViewName("401");
        return mv;
    }
}
